<?php defined('SYSPATH') or die('No direct script access.');

class Model_ProductParser_FromShop_Wildberries extends Model_ProductParser_Abstract
{   
    protected static $_instance = null;
    
    protected $_product = null;
 
    public function parse(Model_Product $product)
    {
        $this->_product = $product;
        
        $url  = $this->_get_clean_product_url();
        
        $html = $this->_get_source_code($url);
        
        $html = $this->_encode($html);
        
        /*try {
            DB::insert('product_html', array('product_id', 'html'))
                ->values(array($this->_product->id, $html))
                ->execute();
        } catch (Database_Exception $e) {
            if (strstr($e->getMessage(), 'Duplicate entry') !== false) {
                DB::update('product_html')
                    ->set(array('html' => $html))
                    ->where('product_id', '=', $this->_product->id)
                    ->execute();    
            } else {
                die($e->getMessage());    
            }
            
        } */
        
        try {
            $color          = $this->_get_color($html);
            $consist        = $this->_get_consist($html);       
            $color_products = $this->_get_color_products($html);      
            $images         = $this->_get_images($html);        
            $params         = $this->_get_params($html);
            $sizes          = $this->_get_sizes($html);
            $reviews        = $this->_get_reviews($html);
        } catch (Exception $e) {
            echo 'Error - product #'.$this->_product->id.'. '.$e->getMessage();
			die();
        }
        
        if ($color) {
            $params['Цвет'] = $color;   
        }
        if ($consist) {
            $params['Состав'] = $consist;    
        }
        if (count($sizes)) {
            $params['размер'] = implode(', ', $sizes);    
        }
        $images = implode('||', $images);
        if (count($params)) {
            $params = json_encode($params);
            $clean_params = Model_Product::get_clean_params($params);    
        } else {
            $params = $clean_params = null;
        }
        
        DB::update('product_data')
                ->set(array(
                        'images' => $images,
                        'params' => $params,
                        'clean_params' => $clean_params,
                ))
                ->where('product_id', '=', $this->_product->id)
                ->execute();  
                
        if (count($color_products)) {
            $products = ORM::factory('product')
                            ->where('shop_id', '=', $this->_product->shop_id)
                            ->where('original_id', 'IN', $color_products)
                            ->find_all();
            foreach ($products as $product) {
                if ($this->_product->id != $product->id) {
                    DB::insert('product_differentcolors', array('product_id', 'product_id2'))
                                ->values(array($this->_product->id, $product->id))->execute();  
                } 
            }   
        }
        
        foreach ($reviews as $review) {
            ORM::factory('product_review_wildberries')->add_review($this->_product, $review['text'], $review['rating'],
                    $review['user_nick'], $review['link'], $review['date'], $review['u_yes'], $review['u_no']);    
        }
        
        /*echo '<pre>';
        print_r($color_products);
        print_r($images);
        print_r(json_decode($params, true)); 
        print_r($reviews);*/  
    }
    
    protected function _get_clean_product_url()
    {
        // https://ad.admitad.com/goto/1d9ed345ddea57d2938cdc28f2033d/?ulp=http%3A%2F%2Fwww.wildberries.ru%2Fcatalog%2F1210559%2Fdetail.aspx
        // http%3A%2F%2Fwww.wildberries.ru%2Fcatalog%2F1210559%2Fdetail.aspx
        // http%3A%2F%2Fwww.wildberries.ru%2Fcatalog%2F1210559%2Fdetail.aspx
        
        $url = $this->_product->url;
        if (strstr($url, 'admitad.com') !== false) {
            $delimeter = '?ulp=';
            $pos = strpos($url, $delimeter) + strlen($delimeter);
            $url = substr($url, $pos);
            $url = str_replace(array('%3A', '%2F'), array(':', '/'), $url);
        }
        return $url;
    }
    
    protected function _encode($text)
    {
        return iconv('cp1251', 'utf-8', $text);
    }
    
    protected function _get_color($data)
    {
        return $this->_cut_str('class="color">', '</span>', $data);    
    }
    
    protected function _get_consist($data)
    {
        return $this->_cut_str('class="composition">', '</span>', $data);    
    }
        
    protected function _get_color_products($data)
    {
        $colors = array();
        $data = $this->_cut_str('<div id="colorpicker">', '</div>', $data);
        
        while ($color = $this->_cut_str('<li ', '</li>', $data)) {
            if ($color = $this->_cut_str('<a href="http://www.wildberries.ru/catalog/', '/detail.aspx">', $color)) {
                $colors[] = $color;    
            }    
        } 
        return $colors;   
    }  
        
    protected function _get_images($data)
    { 
        $images = array();
              
        $data = $this->_cut_str('<ul class="carousel"', '</ul>', $data);
        while ($image = $this->_cut_str('<li>', '</li>', $data)) {
            $image = $this->_cut_str('rev="', '"', $image);
            if ($image) {
                $images[] = $image;   
            }        
        } 
        return $images; 
    }
        
    protected function _get_params($data)
    {
        $params = array();
              
        $data = $this->_cut_str('<table class="pp-additional">', '</table>', $data);
        while ($param = $this->_cut_str('<tr', '</tr>', $data)) {
            $name  = trim(str_replace(':', '', $this->_cut_str('<td>', '</td>', $param)));
            $value = trim($this->_cut_str('<td>', '</td>', $param));
            
            if ($name && $value) {
                $params[$name] = $value;   
            }        
        } 
        return $params;    
    }
    
    protected function _get_sizes($data)
    { 
        $sizes = array();
              
        $data = $this->_cut_str('<div id="GoodCharacteristic" data-sizeless=\'false\'', '</div>', $data);
        while ($size = $this->_cut_str('<label', '/label>', $data)) {
            $size = $this->_cut_str('>', '<', $size);
            $size = trim(strip_tags($size));
            $sizes[] = $size;       
        } 
        return $sizes; 
    }
    
    protected function _get_reviews($data)
    { 
        $reviews = array();         
        $data = $this->_cut_str('<div id="comments-list" class="comments-tab" itemprop="reviews"', '<div id="rules" class="jqmWindow"', $data);
        while ($_review = $this->_cut_str('<div class="comment OneCommentItem"', '</span>
                </div>
            </div>
', $data)) {
            $_review .= '</span>';
           
            $usefulness = $this->_get_review_usefulness($_review);
            $review = array( 
                'user_nick' => $this->_get_review_user_nick($_review),
                'rating'    => $this->_get_review_rating($_review),
                'text'      => $this->_get_review_text($_review),
                'link'      => str_replace('detail.aspx', 'detail.aspx#comments_list', $this->_product->url),   // урл товара + #comments_list
                'date'      => $this->_get_review_date($_review),
                'u_yes'     => $usefulness['u_yes'],
                'u_no'      => $usefulness['u_no'], 
            );
            $reviews[] = $review;
        } 
        return $reviews; 
    }
    
    protected function _get_review_user_nick($review_data)
    {
        $name = Model_ProductParser_Abstract::_cut_str('<span itemprop="author" class="username">', '</span>', $review_data);
        return trim(strip_tags($name));  
    }
    
    protected function _get_review_rating($review_data)
    {
        return trim(Model_ProductParser_Abstract::_cut_str(' itemprop="reviewRating">', '</div>', $review_data));
    }
    
    protected function _get_review_text($review_data)
    {
        return trim(Model_ProductParser_Abstract::_cut_str('<p itemprop="reviewBody" class="body">', '</p>', $review_data));  
    }
    
    protected function _get_review_date($review_data)
    {
        $months = array(
            'января'    => '01',
            'февраля'   => '02',
            'марта'     => '03',
            'апреля'    => '04',
            'мая'       => '05',
            'июня'      => '06',
            'июля'      => '07',
            'августа'   => '08',
            'сентября'  => '09',
            'октября'   => '10',
            'ноября'    => '11',
            'декабря'   => '12',
        );
    
        if ($date = trim(Model_ProductParser_Abstract::_cut_str('itemprop="publishDate">', '</div>', $review_data))) {
            //18 сентября, 16:16
            //18 сентября 2013, 16:16
            $parts = explode(', ', $date);
            $result = array();
            
            $date_parts = explode(' ', $parts[0]);
            if (count($date_parts) == 2) {
                $result['d'] = $date_parts[0];
                $result['m'] = $months[$date_parts[1]];
                $result['y'] = date('Y');        
            } else if (count($date_parts) == 3) {
                $result['d'] = $date_parts[0];
                $result['m'] = $months[$date_parts[1]];
                $result['y'] = $date_parts[2];    
            }
            
            $date = strtotime(implode('-', $result).' '.$parts[1]);
            if ($date) {
                return $date;
            }       
        }
        return null;  
    }
    
    protected function _get_review_usefulness($review_data)
    {
        $usefulness = array(
            'u_yes' => 0,
            'u_no'  => 0,
        );
        
		$review_data = $review_data.'<!--end-->';
        $u = Model_ProductParser_Abstract::_cut_str('<span class="wrapper">Отзыв полезен?', '</span><!--end-->', $review_data);
        $parts = explode('/', strip_tags($u));
		$usefulness['u_yes'] = trim(str_replace('Да', '', $parts[0]));
		$usefulness['u_no']  = trim(str_replace('Нет', '', $parts[1]));
        return $usefulness; 
    }
}